<template>
  <div v-loading="loading" class="limited-time-offers-form-main">

    <!-- head start -->
    <div class="head-container">
      <div class="flex-x-start-center">
        <div class="title">{{ storeInfo.name }} / {{ typeOptions[form.type] }} / {{ titleOptions[mode] }}</div>
        <el-button-group>
          <el-button
            size="small"
            round
            @click="back"
          >返回
          </el-button>
          <el-button
            v-if="mode!=='detail'"
            type="primary"
            size="small"
            round
            @click="submitForm"
          >保存
          </el-button>
        </el-button-group>
      </div>
      <el-divider />
    </div>
    <!-- head end -->

    <!-- form start -->
    <div class="form-container">
      <el-scrollbar style="height:100%" class="hid-scrollbar-x">
        <el-form
          ref="form"
          :rules="rules"
          :model="form"
          :disabled="mode==='detail'"
          label-position="right"
          size="small "
          label-width="150px"
        >
          <!--商品 start-->
          <el-divider content-position="left">商品</el-divider>
          <el-form-item label="活动名称：" prop="name">
            <el-input v-model="form.name" maxlength="30" class="w-500" clearable show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="活动日期：" prop="activityDate">
            <el-date-picker
              v-model="form.activityDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <!--SEC_KILL-->
          <div v-if="['SEC_KILL'].includes(form.type)">
            <el-form-item label="活动时间：" prop="periodTimeList">
              <div
                v-for="(v,i) in form.periodTimeList"
                :key="'time'+i"
                style="margin-bottom: 10px"
              >
                <!--<el-time-picker-->
                <!--  v-model="form.periodTimeList[i].activityTime"-->
                <!--  is-range-->
                <!--  value-format="HH"-->
                <!--  format="HH:mm"-->
                <!--  range-separator="~"-->
                <!--  start-placeholder="开始时间"-->
                <!--  end-placeholder="结束时间"-->
                <!--  placeholder="选择时间范围"-->
                <!--/>-->
                <el-time-select
                  v-model="form.periodTimeList[i].beginTime"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '24:00'
                  }"
                  placeholder="起始时间"
                />
                <span>&nbsp;至&nbsp;</span>
                <el-time-select
                  v-model="form.periodTimeList[i].endTime"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '24:00',
                  }"
                  placeholder="结束时间"
                />
                <el-button
                  v-if="mode!=='detail'&&form.periodTimeList.length>1"
                  type="text"
                  icon="el-icon-delete"
                  class="app-text-color-danger"
                  @click="handleDelLimitTime(i)"
                >删除
                </el-button>
                <el-button
                  v-if="mode!=='detail'&&form.periodTimeList.length===(i+1)"
                  type="text"
                  icon="el-icon-plus"
                  class="app-text-color-primary"
                  @click="handleAddLimitTime"
                >添加
                </el-button>
              </div>
              <div v-if="mode!=='detail'" class="app-tips">请按照24小时制输入可用时段</div>
            </el-form-item>
            <el-form-item label="活动商品：" prop="skuList">
              <div style="margin-bottom: 10px">
                <el-button v-if="mode!=='detail'" type="primary" round size="small" @click="handleChooseProduct">
                  选择商品
                </el-button>
                <el-button v-if="mode!=='detail'" :disabled="!form.skuList.length" type="text" round size="small" @click="handleSetPrice('price','设置秒杀价')">
                  设置秒杀价
                </el-button>
                <el-button v-if="mode!=='detail'" :disabled="!form.skuList.length" type="text" round size="small" @click="handleSetStock('baseStock','设置最大可秒杀商品数')">
                  设置最大可秒杀商品数
                </el-button>
              </div>
              <!--<el-tag type="success">商品如有搭配销售的配件，注意拼团下单时只会判断主商品的拼团库存，默认所有搭配商品都是库存不限的</el-tag>-->
              <div v-if="form.skuList.length" class="flex-x-start-center goods-content">
                <el-image :src="fileBaseUrl+form.goodsCover" style="width: 100px; height: 100px;margin-right: 10px" fit="contain" />
                <div>
                  <div class="name">{{ form.goodsTitle }}</div>
                  <div class="category app-tips">
                    {{ form.categoryName && form.categoryName.join('/') || '无类目' }}
                  </div>
                </div>
              </div>
              <el-table :data="form.skuList" border size="small" empty-text="未选择商品">
                <el-table-column prop="skuInfo" label="属性">
                  <template slot-scope="scope">
                    {{ JSON.parse(scope.row.skuInfo).join(' / ') || '无' }}
                  </template>
                </el-table-column>
                <el-table-column prop="originPrice" label="市场价/元">
                  <template slot-scope="scope">
                    {{ scope.row.originPrice ? scope.row.originPrice / 100 : '无' }}
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="秒杀价/元" width="200px">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="rules.skuPrice"
                      :prop="'skuList.' + scope.$index + '.price'"
                      style="margin-top: 18px"
                    >
                      <el-input
                        v-model.trim="scope.row.price"
                        clearable
                        maxlength="8"
                        placeholder="秒杀价"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="curStockNum" label="现有库存">
                  <template slot="header" slot-scope="scope">
                    <span>现有库存</span>
                    <el-popover placement="top-start" width="300" trigger="hover">
                      <div>现有库存指商品在当前店铺的总库存，用于做配置秒杀库存的参考</div>
                      <i
                        slot="reference"
                        class="el-icon-warning app-text-color-info"
                        style="font-size:16px;"
                      />
                    </el-popover>
                  </template>
                </el-table-column>

                <el-table-column prop="baseStock" label="库存" width="200px">
                  <template slot="header" slot-scope="scope">
                    <span>最大可秒杀商品数</span>
                    <el-popover placement="top-start" width="300" trigger="hover">
                      <div>最大可秒杀商品数指当前秒杀活动参与秒杀的商品最大数量限制, 可以大于现有商品库存，详情请参考库存配置项</div>
                      <i
                        slot="reference"
                        class="el-icon-warning app-text-color-info"
                        style="font-size:16px;"
                      />
                    </el-popover>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="rules.skuBaseStock"
                      :prop="'skuList.' + scope.$index + '.baseStock'"
                      style="margin-top: 18px"
                    >
                      <el-input
                        v-model.trim="scope.row.baseStock"
                        maxlength="5"
                        clearable
                        placeholder="秒杀库存"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="skuDeleted" label="sku状态">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.skuDeleted" size="small" type="danger">已失效</el-tag>
                    <el-tag v-else size="small">正常</el-tag>
                  </template>
                </el-table-column>
                <el-table-column v-if="mode!=='detail'" prop="price" label="操作" width="100px">
                  <template slot-scope="scope">
                    <el-button type="text" class="app-text-color-danger" @click="handleRemoveSkuList(scope.$index)">移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
          <!--GROUP-->
          <div v-if="['GROUP'].includes(form.type)">
            <div>
              <el-form-item label="成团人数：" prop="configForm.groupJoinNum">
                <el-input v-model="form.configForm.groupJoinNum" maxlength="2" clearable class="w-200" placeholder="请输入">
                  <template slot="append">人</template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item label="活动商品：" prop="skuList">
              <div style="margin-bottom: 10px">
                <el-button v-if="mode!=='detail'" type="primary" round size="small" @click="handleChooseProduct">
                  选择商品
                </el-button>
                <el-button v-if="mode!=='detail'" :disabled="!form.skuList.length" type="text" round size="small" @click="handleSetPrice('price','设置拼团价')">
                  设置拼团价
                </el-button>
                <el-button v-if="mode!=='detail'" :disabled="!form.skuList.length" type="text" round size="small" @click="handleSetPrice('specialPrice','设置团长优惠价')">
                  设置团长优惠价
                </el-button>
              </div>
              <div v-if="form.skuList.length" class="flex-x-start-center goods-content">
                <el-image :src="fileBaseUrl+form.goodsCover" style="width: 100px; height: 100px;margin-right: 10px" fit="contain" />
                <div>
                  <div class="name">{{ form.goodsTitle }}</div>
                  <div class="category app-tips">
                    {{ form.categoryName && form.categoryName.join('/') || '无类目' }}
                  </div>
                </div>
              </div>

              <el-table :data="form.skuList" border style="width: 900px" size="small" empty-text="未选择商品">
                <el-table-column prop="skuInfo" label="属性">
                  <template slot-scope="scope">
                    {{ JSON.parse(scope.row.skuInfo).join(' / ') || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="originPrice" label="市场价/元">
                  <template slot-scope="scope">
                    {{ scope.row.originPrice ? scope.row.originPrice / 100 : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="拼团价/元">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="rules.skuPrice"
                      :prop="'skuList.' + scope.$index + '.price'"
                      style="margin-top: 18px"
                    >
                      <el-input
                        v-model.trim="scope.row.price"
                        placeholder="拼团价"
                        clearable
                        maxlength="8"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="团长优惠价/元">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="rules.specialPrice"
                      :prop="'skuList.' + scope.$index + '.specialPrice'"
                      style="margin-top: 18px"
                    >
                      <el-input
                        v-model.trim="scope.row.specialPrice"
                        placeholder="团长优惠价"
                        clearable
                        maxlength="8"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="curStockNum" label="现有库存">
                  <!--<template slot="header" slot-scope="scope">-->
                  <!--  <span>现有库存</span>-->
                  <!--  <el-popover placement="top-start" width="300" trigger="hover">-->
                  <!--    <div>现有库存指商品在当前店铺的总库存，用于做配置拼团库存的参考</div>-->
                  <!--    <i-->
                  <!--      slot="reference"-->
                  <!--      class="el-icon-warning app-text-color-info"-->
                  <!--      style="font-size:16px;"-->
                  <!--    />-->
                  <!--  </el-popover>-->
                  <!--</template>-->
                </el-table-column>
                <el-table-column prop="skuDeleted" label="sku状态">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.skuDeleted" size="small" type="danger">已失效</el-tag>
                    <el-tag v-else size="small">正常</el-tag>
                  </template>
                </el-table-column>
                <el-table-column v-if="mode!=='detail'" prop="price" label="操作" width="60px">
                  <template slot-scope="scope">
                    <el-button type="text" class="app-text-color-danger" @click="handleRemoveSkuList(scope.$index)">移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
          <!--商品 end-->

          <!--顾客 start-->
          <el-divider content-position="left">顾客</el-divider>
          <template v-if="['SEC_KILL'].includes(form.type)">
            <el-form-item :label="['SEC_KILL'].includes(form.type)?'参与对象':'拼团要求'" prop="configForm.userLimitCards">
            <el-radio v-model="form.configForm.userLimit" :label="0">所有人</el-radio>
            <el-radio v-model="form.configForm.userLimit" :label="1">所有会员</el-radio>
            <el-radio v-model="form.configForm.userLimit" :label="2">指定会员等级</el-radio>
            <el-collapse-transition>
              <div v-if="form.configForm.userLimit===2" class="nest-card-box">
                <el-card>
                  <el-checkbox-group v-model="form.configForm.userLimitCards">
                    <el-checkbox
                      v-for="item in memberCardOptions"
                      :key="item.id"
                      :label="item.id"
                    >{{ item.status ? item.categoryName : item.categoryName + "(已停用)" }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-card>
              </div>
            </el-collapse-transition>
          </el-form-item>
          </template>
          <template v-else-if="form.skuList.length < 1">
            <el-form-item label="拼团要求" prop="configForm.userLimitCards" >
              <el-button v-if="form.skuList.length < 1" type="text" disabled>请先选择商品</el-button>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="拼团要求" prop="configForm.userLimitCards" v-if="form.goodsType == 100&&!form.virtualGoods">
            <el-radio v-model="form.configForm.userLimit" :label="0">所有人</el-radio>
            <el-radio v-model="form.configForm.userLimit" :label="1">所有会员</el-radio>
            <el-radio v-model="form.configForm.userLimit" :label="2">指定会员等级</el-radio>
            <el-collapse-transition>
              <div v-if="form.configForm.userLimit===2" class="nest-card-box">
                <el-card>
                  <el-checkbox-group v-model="form.configForm.userLimitCards">
                    <el-checkbox
                      v-for="item in memberCardOptions"
                      :key="item.id"
                      :label="item.id"
                    >{{ item.status ? item.categoryName : item.categoryName + "(已停用)" }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-card>
              </div>
            </el-collapse-transition>
          </el-form-item>
          <el-form-item label="拼团要求" prop="configForm.userLimitCards" v-else>
            <el-button v-if="form.skuList.length < 1" type="text" disabled>请先选择商品</el-button>
            <div v-else>
              <el-radio v-model="form.configForm.userLimit" :label="1" :disabled="true" v-if="form.configForm.userLimit === 1">所有会员</el-radio>
              <el-radio v-model="form.configForm.userLimit" :label="2" :disabled="true" v-if="form.configForm.userLimit === 2">指定会员等级</el-radio>
              <el-collapse-transition>
                <div v-if="form.configForm.userLimit===2" class="nest-card-box">
                  <el-card>
                    <el-checkbox-group v-model="form.configForm.userLimitCards" :disabled="true">
                      <el-checkbox
                        v-for="item in memberCardOptions"
                        :key="item.id"
                        :label="item.id"
                      >{{ item.status ? item.categoryName : item.categoryName + "(已停用)" }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-card>
                </div>
              </el-collapse-transition>
            </div>
          </el-form-item>
          </template>
          <template v-if="['GROUP'].includes(form.type)">
            <el-form-item style="margin-bottom: 0;height: 50px" label="顾客限购：" v-if="form.goodsType == 100&&!form.virtualGoods">
            <el-switch
              v-model="form.configForm.perUserLimitSwitch"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changePerUserLimit"
            />
            <span v-if="form.configForm.perUserLimitSwitch">
              <span>&nbsp;活动顾客每人限购&nbsp;</span>
              <el-form-item prop="configForm.perUserLimit" style="display: inline-block">
                <el-input v-model="form.configForm.perUserLimit" maxlength="3" clearable class="w-200" placeholder="请输入1~100" @change="changePerUserLimit">
                  <template slot="append">件</template>
                </el-input>
              </el-form-item>
            </span>
            <span class="app-tips">&nbsp;&nbsp;开关关闭则顾客不限购</span>
            <!--<span class="app-tips">&nbsp;&nbsp;开关关闭则默认按照原商品设置的限购</span>-->
          </el-form-item>
          <el-form-item style="margin-bottom: 0;height: 50px" label="订单限购："  v-if="form.goodsType == 100&&!form.virtualGoods">
            <el-switch
              v-model="form.configForm.perOrderLimitSwitch"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span v-if="form.configForm.perOrderLimitSwitch">
              <span>&nbsp;单笔订单限购&nbsp;</span>
              <el-form-item prop="configForm.perOrderLimit" style="display: inline-block">
                <el-input v-model="form.configForm.perOrderLimit" maxlength="3" clearable class="w-200" placeholder="请输入1~100">
                  <template slot="append">件</template>
                </el-input>
              </el-form-item>
            </span>
            <span class="app-tips">&nbsp;&nbsp;开关关闭则默认单笔订单购买数量不高于顾客限购数量</span>
          </el-form-item>
          </template>
          <template v-else>
            <el-form-item style="margin-bottom: 0;height: 50px" label="顾客限购：" >
            <el-switch
              v-model="form.configForm.perUserLimitSwitch"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changePerUserLimit"
            />
            <span v-if="form.configForm.perUserLimitSwitch">
              <span>&nbsp;活动顾客每人限购&nbsp;</span>
              <el-form-item prop="configForm.perUserLimit" style="display: inline-block">
                <el-input v-model="form.configForm.perUserLimit" maxlength="3" clearable class="w-200" placeholder="请输入1~100" @change="changePerUserLimit">
                  <template slot="append">件</template>
                </el-input>
              </el-form-item>
            </span>
            <span class="app-tips">&nbsp;&nbsp;开关关闭则顾客不限购</span>
            <!--<span class="app-tips">&nbsp;&nbsp;开关关闭则默认按照原商品设置的限购</span>-->
          </el-form-item>
          <el-form-item style="margin-bottom: 0;height: 50px" label="订单限购：">
            <el-switch
              v-model="form.configForm.perOrderLimitSwitch"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span v-if="form.configForm.perOrderLimitSwitch">
              <span>&nbsp;单笔订单限购&nbsp;</span>
              <el-form-item prop="configForm.perOrderLimit" style="display: inline-block">
                <el-input v-model="form.configForm.perOrderLimit" maxlength="3" clearable class="w-200" placeholder="请输入1~100">
                  <template slot="append">件</template>
                </el-input>
              </el-form-item>
            </span>
            <span class="app-tips">&nbsp;&nbsp;开关关闭则默认单笔订单购买数量不高于顾客限购数量</span>
          </el-form-item>
          </template>
         
          <!--顾客 end-->

          <!--库存 start-->
          <div v-if="['SEC_KILL'].includes(form.type)">
            <el-divider content-position="left">库存</el-divider>
            <el-form-item label="商品总库存关联：" prop="configForm.stockReduce">
              <el-switch
                v-model="form.configForm.stockReduce"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <div class="app-tips">
                默认开启，通过秒杀销售的商品会同时扣除商品的主库存(即上面配置中可见的现有库存)，关闭后将系统将只会判断活动限制是否已经到达上限，而不会判断总库存是否足够，有可能出现超卖的情况！
              </div>
            </el-form-item>
            <el-form-item label="每天重置最大可拼团商品数：" prop="configForm.stockUpdatePerDay">
              <span slot="label">
                每天重置最大&nbsp;&nbsp;&nbsp;
                <br>
                可秒杀商品数：
              </span>
              <el-switch
                v-model="form.configForm.stockUpdatePerDay"
                :active-value="1"
                :inactive-value="0"
                :disabled="form.configForm.stockUpdatePerPeriod===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <div class="app-tips">默认关闭，开启则表示每天 00:00 更新最大可秒杀的商品数为预设值，比如预设100件，
                则活动期间每天都要100件商品参与秒杀,抢完即止；如果你关联了商品总库存，请注意总库存数量充足，总库存扣完后会停止秒杀活动！
              </div>
              <div class="app-tips">该规则与每个时段重置最大可秒杀商品数规则互斥，仅支持同时生效一种规则！</div>
            </el-form-item>
            <el-form-item label="每个时段重置最大可秒杀商品数：" prop="configForm.stockUpdatePerPeriod">
              <span slot="label">
                每个时段重置最大&nbsp;&nbsp;&nbsp;
                <br>
                可秒杀商品数：
              </span>
              <el-switch
                v-model="form.configForm.stockUpdatePerPeriod"
                :active-value="1"
                :inactive-value="0"
                :disabled="form.configForm.stockUpdatePerDay===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <div class="app-tips">默认关闭，开启则表示个秒杀时间段前更新最大可秒杀的商品数为预设值；如果你关联了商品总库存， 请注意总库存数量充足，总库存扣完后会停止秒杀活动！</div>
              <div class="app-tips">该规则与每天重置最大可秒杀商品数互斥，仅支持同时生效一种规则！</div>
            </el-form-item>
          </div>
          <!--库存 end-->

          <!--成团 start-->
          <div v-if="['GROUP'].includes(form.type)">
            <el-divider content-position="left">成团</el-divider>
            <el-form-item label="凑团：" prop="configForm.groupRecommend">
              <el-switch
                v-model="form.configForm.groupRecommend"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启后用户可以在商品页面看到其他顾客已经发起的拼团订单</span>
            </el-form-item>
            <el-form-item label="模拟凑团：" prop="configForm.groupRecommendVirtual">
              <el-switch
                v-model="form.configForm.groupRecommendVirtual"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启后用户如果没有可以直接凑团的真实订单，系统将模拟订单团让用户凑团</span>
            </el-form-item>
            <el-form-item label="模拟成团：" prop="configForm.groupAuto">
              <el-switch
                v-model="form.configForm.groupAuto"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启后如果用户的拼团订单长时间没有拼成，系统将会按以下规则添加匿名买家凑满该团</span>
            </el-form-item>
            <div v-if="form.configForm.groupAuto">
              <el-form-item label=" " prop="configForm.groupAutoRuleCheckBox">
                <el-checkbox-group v-model="form.configForm.groupAutoRuleCheckBox" @change="changeGroupAutoRuleCheckBox">
                  <div>
                    <el-checkbox label="groupAutoAfterCreate">
                      <span>所有未成团订单在拼团开始后&nbsp;</span>
                      <el-form-item prop="configForm.groupAutoAfterCreate" style="display: inline-block">
                        <el-input v-model="form.configForm.groupAutoAfterCreate" :disabled="!form.configForm.groupAutoRuleCheckBox.includes('groupAutoAfterCreate')" maxlength="3" class="w-200" placeholder="请输入">
                          <template slot="append">分钟</template>
                        </el-input>
                      </el-form-item>
                      <span>&nbsp;自动成团</span>
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox label="groupAutoBeforeClose">
                      <span>参团人数≥&nbsp;</span>
                      <el-form-item prop="configForm.groupAutoBeforeNum" style="display: inline-block">
                        <el-input v-model="form.configForm.groupAutoBeforeNum" :disabled="!form.configForm.groupAutoRuleCheckBox.includes('groupAutoBeforeClose')" maxlength="2" class="w-200" placeholder="请输入">
                          <template slot="append">人</template>
                        </el-input>
                      </el-form-item>
                      <span>&nbsp;的订单在订单过期前&nbsp;</span>
                      <el-form-item prop="configForm.groupAutoBeforeClose" style="display: inline-block">
                        <el-input v-model="form.configForm.groupAutoBeforeClose" :disabled="!form.configForm.groupAutoRuleCheckBox.includes('groupAutoBeforeClose')" maxlength="3" class="w-200" placeholder="请输入">
                          <template slot="append">分钟</template>
                        </el-input>
                      </el-form-item>
                      <span>&nbsp;自动成团</span>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </div>
          <!--成团 end-->

          <!--优惠 start-->
          <el-divider content-position="left">优惠</el-divider>
          <div v-if="['GROUP'].includes(form.type)">
            <el-form-item label="团长优惠：" prop="configForm.groupLeaderDiscount">
              <el-switch
                v-model="form.configForm.groupLeaderDiscount"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeGroupLeaderDiscount"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示团长享受开团优惠，请在上方价格价格设置团长优惠价；注意模拟成团的团长也会享受优惠价</span>
            </el-form-item>
          </div>
          <el-form-item label="参与其他单品优惠：" prop="configForm.singleGoodsDiscount">
            <el-switch
              v-model="form.configForm.singleGoodsDiscount"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="app-tips">&nbsp;&nbsp;默认开启，开启则表示{{typeOptions[activityType]}}商品可参与其他单品优惠</span>
          </el-form-item>
          <el-form-item label="参与其他订单优惠：" prop="configForm.otherOrderDiscount">
            <el-switch
              v-model="form.configForm.otherOrderDiscount"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="app-tips">&nbsp;&nbsp;默认开启，开启则表示{{typeOptions[activityType]}}商品可参与其他订单优惠，比如会员折扣，积分抵现，代金券，折扣券等</span>
          </el-form-item>
          <el-form-item label="参与支付积分：" prop="configForm.consumeAward">
            <el-switch
              v-model="form.configForm.consumeAward"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="app-tips">&nbsp;&nbsp;默认开启，开启则表示{{typeOptions[activityType]}}商品订单完成后可以参与支付积分活动</span>
          </el-form-item>
          <!--优惠 end-->

          <div v-if="['SEC_KILL'].includes(form.type)">
            <!--预约 start-->
            <el-divider content-position="left">预约</el-divider>
            <el-form-item label="需要预约：" prop="booking">
              <el-switch
                v-model="form.booking"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示需要先预约才可以参与秒杀</span>
            </el-form-item>
            <div v-if="form.booking">
              <el-form-item label="预约截止时间：" prop="bookingTime">
                <el-date-picker
                  v-model="form.bookingTime"
                  value-format="yyyy-MM-dd HH:mm"
                  format="yyyy-MM-dd HH:mm"
                  type="datetime"
                  placeholder="选择日期"
                />
                <span class="app-tips">&nbsp;&nbsp;注意：秒杀截止时间应该小于活动截止时间，一般建议在活动开始时间前</span>
              </el-form-item>
              <el-form-item label="预约方式：" prop="bookingWay">
                <el-select v-model="form.bookingWay" filterable placeholder="请选择" class="w-200">
                  <el-option :value="0" label="默认方式" />
                  <el-option :value="1" label="需要授权手机号" />
                </el-select>
                <span class="app-tips">&nbsp;&nbsp;默认模式：用户点击预约按钮即可完成预约</span>
              </el-form-item>
            </div>
            <!--预约 end-->

            <!--售后 start-->
            <el-divider content-position="left">支付和售后</el-divider>
            <el-form-item label="限时支付：" prop="configForm.payDeadline">
              <el-switch
                v-model="form.configForm.payDeadlineSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span v-if="form.configForm.payDeadlineSwitch">
                <span>提交订单需要在&nbsp;</span>
                <el-input v-model="form.configForm.payDeadline" maxlength="2" clearable class="w-200" placeholder="请输入">
                  <template slot="append">分钟</template>
                </el-input>
                <span>&nbsp;内完成支付</span>
              </span>
              <span class="app-tips">&nbsp;&nbsp;开关关闭则默认15分钟</span>
            </el-form-item>
            <el-form-item label="发货前取消订单：" prop="configForm.cancelRule">
              <el-switch
                v-model="form.configForm.cancelRule"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <span class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示用户支付后可取消订单</span>
            </el-form-item>
          <!--售后 end-->
          </div>
          <div v-if="['GROUP'].includes(form.type) && (form.goodsType == 100&&!form.virtualGoods)">
            <div v-for="(v,i) in form.deliveryList" :key="'deliveryList_'+i">
              <el-divider v-if="v.deliveryType==='EXPRESS'" content-position="left">快递订单</el-divider>
              <el-divider v-if="v.deliveryType==='LOCAL'" content-position="left">同城订单</el-divider>
              <el-divider v-if="v.deliveryType==='SELF_PICKUP'" content-position="left">自提订单</el-divider>
              <el-form-item :prop="'deliveryList.'+i+'supply'">
                <span slot="label">
                  <span v-if="v.deliveryType==='EXPRESS'">快递支持：</span>
                  <span v-if="v.deliveryType==='LOCAL'">同城配送支持：</span>
                  <span v-if="v.deliveryType==='SELF_PICKUP'">自提支持：</span>
                </span>
                <el-switch
                  v-model="v.supply"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="changeDeliverySupply"
                />
                <span v-if="v.deliveryType==='EXPRESS'" class="app-tips">&nbsp;&nbsp;默认开启，快递下单时可以拼团</span>
                <span v-if="v.deliveryType==='LOCAL'" class="app-tips">&nbsp;&nbsp;默认关闭，同城送货上门下单时可以拼团</span>
                <span v-if="v.deliveryType==='SELF_PICKUP'" class="app-tips">&nbsp;&nbsp;默认关闭，到店自提下单时可以拼团</span>
              </el-form-item>

              <el-collapse-transition>
                <div v-if="v.supply">
                  <div v-if="v.deliveryType==='EXPRESS'">
                    <el-form-item :style="{'margin-bottom': v.groupExpireTimeSwitch?0:null}" label="拼团有效期：">
                      <el-switch
                        v-model="v.groupExpireTimeSwitch"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                      />
                      <span class="app-tips">&nbsp;&nbsp;默认关闭，所有拼团订单最晚成团时间为2小时</span>
                      <div v-if="v.groupExpireTimeSwitch">
                        <el-form-item :prop="'deliveryList.'+i+'.groupExpireTimeArray'" :rules="rules.groupExpireTimeArray" style="display: inline-block">
                          <el-input v-model="v.groupExpireTimeArray[0]" maxlength="2" clearable class="w-200" placeholder="请输入整数">
                            <template slot="append">天</template>
                          </el-input>
                          <el-input v-model="v.groupExpireTimeArray[1]" maxlength="2" clearable class="w-200" placeholder="请输入整数">
                            <template slot="append">小时</template>
                          </el-input>
                          <el-input v-model="v.groupExpireTimeArray[2]" maxlength="2" clearable class="w-200" placeholder="请输入整数">
                            <template slot="append">分</template>
                          </el-input>
                        </el-form-item>
                      </div>
                    </el-form-item>
                  </div>
                  <el-form-item v-else label="拼团有效期：">
                    <el-tag v-if="v.deliveryType==='LOCAL'">同城配送的拼团下单有效期预设为15分钟，暂时不支持设置</el-tag>
                    <el-tag v-if="v.deliveryType==='SELF_PICKUP'">到店自提的拼团下单有效期预设为15分钟，暂时不支持设置</el-tag>
                  </el-form-item>
                  <el-form-item :prop="'deliveryList.'+i+'leaderCollect'" label="团长代收：">
                    <el-switch
                      v-model="v.leaderCollect"
                      :active-value="1"
                      :inactive-value="0"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    />
                    <span v-if="v.deliveryType==='EXPRESS'||v.deliveryType==='LOCAL'" class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示代收的订单将发货给团长。是用于收货地址相同的买家拼团，比如公司。团员可以免付邮费。商家也可以少发包裹节省成本。虚拟商品不支持代收。</span>
                    <span v-if="v.deliveryType==='SELF_PICKUP'" class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示代收的订单将统一由团长上门自提。虚拟商品不支持代收。</span>
                    <div>
                      <el-checkbox v-model="v.leaderCollectOptional" :disabled="!v.leaderCollect" :true-label="1" :false-label="0">
                        团员可选是否团长代收
                      </el-checkbox>
                    </div>
                  </el-form-item>
                  <div v-if="v.deliveryType.includes('EXPRESS')">
                    <el-form-item label="拼团购买包邮：">
                      <el-switch
                        v-model="v.freightRule"
                        :active-value="1"
                        :inactive-value="0"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                      />
                      <span class="app-tips">&nbsp;&nbsp;默认关闭，运费按照店铺的相关配置，开启则忽略店铺配置，邮费为0</span>
                    </el-form-item>
                  </div>
                  <div v-if="v.deliveryType.includes('LOCAL')">
                    <el-form-item label="拼团免配送费：">
                      <el-switch
                        v-model="v.freightRule"
                        :active-value="1"
                        :inactive-value="0"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                      />
                      <span class="app-tips">&nbsp;&nbsp;默认关闭，运费按照店铺的相关配置，开启则忽略店铺配置，配送费为0</span>
                    </el-form-item>
                  </div>
                </div>
              </el-collapse-transition>

            </div>

          <!--同城 start-->
          <!--<el-divider content-position="left">同城订单</el-divider>-->
          <!--<el-form-item label="同城配送支持：" prop="deliveryList.deliveryTypeLocalSwitch">-->
          <!--  <el-switch-->
          <!--    v-model="form.deliveryList.deliveryTypeLocalSwitch"-->
          <!--    active-color="#13ce66"-->
          <!--    inactive-color="#ff4949"-->
          <!--  />-->
          <!--  <span class="app-tips">&nbsp;&nbsp;默认关闭，同城送货上门下单时可以拼团</span>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="拼团有效期：">-->
          <!--  <el-tag>同城配送的拼团下单有效期预设为15分钟，暂时不支持设置</el-tag>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="团长代收：" prop="deliveryList.leaderCollect">-->
          <!--  <el-switch-->
          <!--    v-model="form.deliveryList.leaderCollect"-->
          <!--    active-color="#13ce66"-->
          <!--    inactive-color="#ff4949"-->
          <!--  />-->
          <!--  <span class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示代收的订单将发货给团长。是用于收货地址相同的买家拼团，比如公司。团员可以免付邮费。商家也可以少发包裹节省成本。虚拟商品不支持代收。</span>-->
          <!--  <div v-if="form.deliveryList.leaderCollect">-->
          <!--    <el-checkbox v-model="form.deliveryList.leaderCollectOptional" :true-label="1" :false-label="0">-->
          <!--      团员可选是否团长代收-->
          <!--    </el-checkbox>-->
          <!--  </div>-->
          <!--</el-form-item>-->
          <!--同城 end-->

          <!--自提 start-->
          <!--<el-divider content-position="left">自提订单</el-divider>-->
          <!--<el-form-item label="自提支持：" prop="deliveryList.deliveryTypeSelfPickupSwitch">-->
          <!--  <el-switch-->
          <!--    v-model="form.deliveryList.deliveryTypeSelfPickupSwitch"-->
          <!--    active-color="#13ce66"-->
          <!--    inactive-color="#ff4949"-->
          <!--  />-->
          <!--  <span class="app-tips">&nbsp;&nbsp;默认关闭，到店自提下单时可以拼团</span>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="拼团有效期：">-->
          <!--  <el-tag>到店自提的拼团下单有效期预设为15分钟，暂时不支持设置</el-tag>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="团长代收：" prop="deliveryList.leaderCollect">-->
          <!--  <el-switch-->
          <!--    v-model="form.deliveryList.leaderCollect"-->
          <!--    active-color="#13ce66"-->
          <!--    inactive-color="#ff4949"-->
          <!--  />-->
          <!--  <span class="app-tips">&nbsp;&nbsp;默认关闭，开启则表示代收的订单将发货给团长。是用于收货地址相同的买家拼团，比如公司。团员可以免付邮费。商家也可以少发包裹节省成本。虚拟商品不支持代收。</span>-->
          <!--  <div v-if="form.deliveryList.leaderCollect">-->
          <!--    <el-checkbox v-model="form.deliveryList.leaderCollectOptional" :true-label="1" :false-label="0">-->
          <!--      团员可选是否团长代收-->
          <!--    </el-checkbox>-->
          <!--  </div>-->
          <!--</el-form-item>-->
          <!--自提 end-->
          </div>
          <div v-if="['GROUP'].includes(form.type)">
            <el-form-item label=" " prop="deliveryList" />
          </div>

        </el-form>
      </el-scrollbar>
    </div>

    <!-- form end -->

    <!--组件-->
    <DialogMallGoodsSkuTable ref="dialogMallGoodsSkuTable" :goods-types="form.type==='SEC_KILL'?[100,200]:[100,200]" :store-id="storeInfo.storeId" :max-goods-num="1" manage-mode="single" />
    <PriceDialog ref="priceDialog" />
    <StockDialog ref="stockDialog" />
  </div>
</template>
<script>
import ValidActivityForm from './mixin/ValidActivityForm'
import PriceDialog from './PriceDialog'
import StockDialog from './StockDialog'
import { mapGetters } from 'vuex'
import { getAllVipCardList } from '@/api/vip'
import { addActivity, activityDetail, updateActivity } from '../../api/activity'

export default {
  components: {
    PriceDialog,
    StockDialog
  },
  mixins: [ValidActivityForm],
  props: {
    activityType: {
      type: String,
      required: true,
      default: 'SEC_KILL'
    },
    storeInfo: {
      type: Object,
      default: () => {
        return {
          storeId: 0,
          name: null
        }
      }
    }
  },
  data() {
    return {
      // 配置
      resolve: null,
      reject: null,
      titleOptions: {
        add: '添加活动',
        edit: '编辑活动',
        detail: '活动详情'
      },
      typeOptions: {
        SEC_KILL: '秒杀',
        GROUP: '拼团'
      },
      // 状态
      loading: false,
      // 数据
      mode: 'add',
      serialNo: null,
      memberCardOptions: [],
      startTime: null,
      endTime: null,
      form: {
        storeId: null,
        type: 'SEC_KILL', // SEC_KILL:拼团, GROUP:拼团
        goodsId: null,
        goodsCover: null,
        goodsTitle: null,
        categoryName: [],
        name: null,
        activityDate: [], // no params
        beginTime: null,
        endTime: null,
        goodsType:100,
        virtualGoods:false,
        periodTimeList: [
          {
            // activityTime: null,
            beginTime: null,
            endTime: null,
            weekDays: '0,1,2,3,4,5,6'
          }
        ], // {activityTime} no params转 {beginTime,endTime,weekDays} Time:单位分钟 weekDay:星期, 逗号分隔, 0: 星期天
        skuList: [
          // {
          //   baseStock: 0, // 基础库存, 0:表示不设置库存, 使用商品库存
          //   categoryName: [],
          //   cover: 'string', // 商品图片, 仅编辑时候返回
          //   goodsId: 0,
          //   originPrice: 0, // 市场价
          //   price: 0, // price
          //   skuId: 0,
          //   skuInfo: 'string',
          //   specialPrice: 0, // 特价(团长价)
          //   title: 'string'
          // }
        ],
        configForm: {
          userLimit: 0, // 购买限制规则, 0:不做限制, 1:会员, 2:指定会员类型
          userLimitCards: [], // userLimitCards
          perUserLimitSwitch: true, // no params
          perUserLimit: null, // 每人限购, 按照活动来计算, 0:表示不做作限制
          perOrderLimitSwitch: true, // no params
          perOrderLimit: null, // 每单限购, 按照活动来计算 0:表示不做作限制
          stockReduce: true, // 关联库存
          stockUpdatePerDay: 0, // 按天更新库存
          stockUpdatePerPeriod: 0, // 按周期性更新库存
          singleGoodsDiscount: true, // 参与其他单品优惠
          otherOrderDiscount: true, // 参与其他订单优惠
          consumeAward: true, // 消费后奖励, 0:奖励, 1:奖励
          payDeadlineSwitch: true, // no params
          payDeadline: 15, // 多少分钟内完成支付
          cancelRule: 0, // 取消规则, 0:支付后不可取消订单, 1:发货前可以取消订单

          groupJoinNum: null, // 拼团人数
          groupRecommend: false, // 拼团推荐
          groupRecommendVirtual: false, // 模拟拼团推荐
          groupAuto: false, // 模拟成团
          groupAutoRuleCheckBox: [], // 模拟成团要求
          groupAutoAfterCreate: null, // 创建订单后,多少分钟模拟成团, 0:表示不模拟
          groupAutoBeforeClose: null, // 拼团关闭前多少分钟,模拟成团
          groupAutoBeforeNum: null, // 自动成团前,至少满足多个人
          groupLeaderDiscount: false // 团长优惠
        },
        booking: false, // 是否需要预约
        bookingTime: null, // 预约开始时间, 非必填, 默认为当前时间, yyyy-MM-dd HH:mm
        bookingWay: 0, // 预约方式, 0: 默认, 1:需要授权手机号
        deliveryList: [
          {
            deliveryType: 'EXPRESS', // 类型
            supply: true, // 是否启用
            freightRule: 0, // 0使用商品邮费  1免邮
            groupExpireTime: null, // 有效期分钟
            groupExpireTimeSwitch: false, // no params 有效期 关闭默认2小时
            groupExpireTimeArray: [null, null, null],
            leaderCollect: 0, // 团长代收
            leaderCollectOptional: 0 // 团长代收是否可选
          },
          {
            deliveryType: 'LOCAL',
            supply: false, // 是否启用
            freightRule: 0, // 0使用商品邮费  1免邮
            groupExpireTime: 15, // 有效期分钟
            groupExpireTimeSwitch: false, // no params 有效期 关闭默认2小时
            groupExpireTimeArray: [null, null, null],
            leaderCollect: 0, // 团长代收
            leaderCollectOptional: 0 // 团长代收是否可选
          },
          {
            deliveryType: 'SELF_PICKUP',
            supply: false, // 是否启用
            freightRule: 0, // 0使用商品邮费  1免邮
            groupExpireTime: 15, // 有效期分钟
            groupExpireTimeSwitch: false, // no params 有效期 关闭默认2小时
            groupExpireTimeArray: [null, null, null],
            leaderCollect: 0, // 团长代收
            leaderCollectOptional: 0 // 团长代收是否可选
          }
        ],
       

      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 打开
    open(mode = 'add', serialNo = null) {
      this.mode = mode
      this.serialNo = serialNo
      this.fetchMemberCardOptions()
      if (serialNo) {
        this.fetchActivityDetail()
      } else {
        this.form.type = this.activityType
      }
      console.log(mode, serialNo)
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    // 获取详情
    fetchActivityDetail() {
      return new Promise((resolve, reject) => {
        this.loading = true
        activityDetail({ serialNo: this.serialNo }).then((res) => {
          const params = res.data
          if (params.type === 'SEC_KILL') {
            // 拼团时间
            params.periodTimeList.forEach(v => {
              // v.activityTime = [this.$options.filters.mm2HHmm(v.beginTime), this.$options.filters.mm2HHmm(v.endTime)]
              v.beginTime = this.$options.filters.mm2HHmm(v.beginTime)
              v.endTime = this.$options.filters.mm2HHmm(v.endTime)
            })
            // 支付时间
            params.configForm.payDeadlineSwitch = params.configForm.payDeadline !== 15
          }
          if (params.type === 'GROUP') {
            // 拼团
            params.configForm.groupAutoRuleCheckBox = []
            if (params.configForm.groupAuto) {
              if (params.configForm.groupAuto) {
                if (params.configForm.groupAutoAfterCreate) {
                  params.configForm.groupAutoRuleCheckBox.push('groupAutoAfterCreate')
                } else {
                  params.configForm.groupAutoAfterCreate = null
                }
                if (params.configForm.groupAutoBeforeClose) {
                  params.configForm.groupAutoRuleCheckBox.push('groupAutoBeforeClose')
                } else {
                  params.configForm.groupAutoBeforeClose = null
                  params.configForm.groupAutoBeforeNum = null
                }
              }
            } else {
              params.configForm.groupAutoAfterCreate = null
              params.configForm.groupAutoBeforeClose = null
              params.configForm.groupAutoBeforeNum = null
            }

            // 配送支持
            params.deliveryList.forEach(v => {
              if (v.supply) {
                if (v.deliveryType === 'EXPRESS') {
                  v.groupExpireTimeSwitch = v.groupExpireTime !== 120
                  const day = Math.floor(v.groupExpireTime / 60 / 24) || null
                  const hour = Math.floor((v.groupExpireTime - day * 24 * 60) / 60) || null
                  const min = v.groupExpireTime - day * 24 * 60 - hour * 60 || null
                  v.groupExpireTimeArray = [day, hour, min]
                } else {
                  v.groupExpireTimeSwitch = false
                  v.groupExpireTime = 15
                  v.groupExpireTimeArray = [null, null, null]
                }
              } else {
                v.groupExpireTimeSwitch = false
                v.groupExpireTime = null
                v.groupExpireTimeArray = [null, null, null]
              }
            })
          }

          // 日期
          params.activityDate = [params.beginTime, params.endTime]

          // sku
          params.skuList.forEach(v => {
            v.price = v.price / 100
            v.specialPrice = v.specialPrice / 100 || null
            if (v.baseStock === 0) v.baseStock = null
          })

          // 限购
          params.configForm.perUserLimitSwitch = params.configForm.perUserLimit !== 0
          params.configForm.perOrderLimitSwitch = params.configForm.perOrderLimit !== 0

          console.log('活动数据', params)
          this.form = params
        }).finally(() => {
          this.loading = false
          resolve()
        })
      })
    },

    // 获取所有会员卡
    fetchMemberCardOptions() {
      return new Promise((resolve, reject) => {
        getAllVipCardList().then((res) => {
          this.memberCardOptions = res.data || []
        }).finally(() => {
          resolve()
        })
      })
    },

    /**
     * 按钮组
     */
    // 返回
    back() {
      this.resolve && this.resolve()
    },

    // 删除活动时间段
    handleDelLimitTime(index) {
      this.form.periodTimeList.splice(index, 1)
      this.$refs.form.validateField('periodTimeList')
    },

    // 新增活动时间段
    handleAddLimitTime() {
      this.form.periodTimeList.push({
        // activityTime: null,
        beginTime: null,
        endTime: null,
        weekDays: '0,1,2,3,4,5,6'
      })
    },

    // 选择商品
    handleChooseProduct() {
      const checkedSkuIds = this.form.skuList.map(v => {
        return v.skuId
      })
      const checkedGoodsIds = this.form.goodsId ? [this.form.goodsId] : []
      this.$refs.dialogMallGoodsSkuTable.open({ checkedSkuIds, checkedGoodsIds }).then(res => {
        const list = res || []
        const skuList = []
        if (list.length) {
          this.$refs.form.clearValidate(['skuList'])
          list.forEach(v => {
            skuList.push({
              curStockNum: v.storeInventory,
              baseStock: null, // 基础库存, 0:表示不设置库存, 使用商品库存
              categoryName: v.goods.category,
              goodsId: v.goods.goodsId,
              originPrice: v.skuInfo.originPrice, // 市场价
              price: null, // price
              skuId: v.skuInfo.skuId,
              skuInfo: JSON.stringify(v.skuInfo.specAttrNameList),
              specialPrice: null, // 特价(团长价)
              baseStockRadio: 0
            })
          })
          if(!['SEC_KILL'].includes(this.form.type)){
            this.form.configForm.userLimit = list[0].goodsBuyRule.memberType
            this.form.configForm.userLimitCards = list[0].goodsBuyRule.memberType == 2?list[0].goodsBuyRule.cardIdList:[]
          }
          let {goods:{goodsId,coverImg:goodsCover,title:goodsTitle,category = [],goodsType}} = list[0]
          this.form = Object.assign(this.form,{goodsId,goodsCover,goodsTitle,categoryName:category,virtualGoods:goodsType == 200 })
          
          
          // this.form.goodsId = list[0].goods.goodsId
          // this.form.goodsCover = list[0].goods.coverImg
          // this.form.goodsTitle = list[0].goods.title
          // this.form.categoryName = list[0].goods.category || []
          this.form.skuList = this.form.skuList.concat(skuList)


        }
      })
      console.log('this.form.skuList', this.form.skuList)
    },

    // 移除sku
    handleRemoveSkuList(index) {
      this.form.skuList.splice(index, 1)
      if (this.form.skuList.length === 0) this.form.goodsId = null
      this.form.goodsType = 100
      this.form.virtualGoods = false
    },

    // 设置sku价格
    handleSetPrice(type, title) {
      this.$refs.priceDialog.open(title).then(res => {
        if (res && res.price) {
          this.form.skuList.forEach(v => {
            v[type] = res.price
          })
        }
      })
    },

    // 设置sku库存
    handleSetStock(type, title) {
      this.$refs.stockDialog.open(title).then(res => {
        if (res && res.stock) {
          this.form.skuList.forEach(v => {
            v[type] = res.stock
          })
        }
      })
    },

    // 保存
    submitForm() {
      console.log(this.form)
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          params.storeId = params.storeId || this.storeInfo.storeId
          // 拼团专属
          if (params.type === 'SEC_KILL') {
            // 拼团时间
            params.periodTimeList.forEach(v => {
              // v.beginTime = this.$options.filters.HHmm2mm(v.activityTime[0])
              // v.endTime = this.$options.filters.HHmm2mm(v.activityTime[1])
              v.beginTime = this.$options.filters.HHmm2mm(v.beginTime)
              v.endTime = this.$options.filters.HHmm2mm(v.endTime)
              // delete v.activityTime
            })
            params.periodTimeList.sort((a, b) => {
              return a.beginTime - b.beginTime
            })

            // 支付时间
            if (!params.configForm.payDeadlineSwitch) params.configForm.payDeadline = 15
            delete params.configForm.payDeadlineSwitch

            // 预约
            if (!params.booking) {
              params.bookingTime = null
              params.bookingWay = 0
            }
          } else {
            params.periodTimeList = []
            params.configForm.stockReduce = true
            params.configForm.stockUpdatePerDay = 0
            params.configForm.stockUpdatePerPeriod = 0
            params.configForm.payDeadline = 15
            params.configForm.cancelRule = 0
            params.booking = false
            params.bookingTime = null
            params.bookingWay = 0
          }

          // 团购专属
          if (params.type === 'GROUP') {
            // 拼团
            if (params.configForm.groupAuto) {
              if (!params.configForm.groupAutoRuleCheckBox.includes('groupAutoAfterCreate')) {
                params.configForm.groupAutoAfterCreate = 0
              }
              if (!params.configForm.groupAutoRuleCheckBox.includes('groupAutoBeforeClose')) {
                params.configForm.groupAutoBeforeClose = 0
                params.configForm.groupAutoBeforeNum = 0
              }
            } else {
              params.configForm.groupAutoAfterCreate = 0
              params.configForm.groupAutoBeforeClose = 0
              params.configForm.groupAutoBeforeNum = 0
            }
            // 配送支持
            params.deliveryList.forEach(v => {
              if (v.supply) {
                if (v.groupExpireTimeSwitch) {
                  v.groupExpireTime = (v.groupExpireTimeArray[0] || 0) * 24 * 60 + (v.groupExpireTimeArray[1] || 0) * 60 + (v.groupExpireTimeArray[2] || 0) * 1
                } else if (v.deliveryType === 'EXPRESS') {
                  v.groupExpireTime = 120
                } else {
                  v.groupExpireTime = 15
                }
              } else {
                v.freightRule = 0
                if (v.deliveryType === 'EXPRESS') {
                  v.groupExpireTime = 120
                } else {
                  v.groupExpireTime = 15
                }
                v.leaderCollect = 0
                v.leaderCollectOptional = 0
              }
              delete v.groupExpireTimeSwitch
              delete v.groupExpireTimeArray
            })
          } else {
            params.deliveryList = []
            params.configForm.groupJoinNum = 0
            params.configForm.groupRecommend = false
            params.configForm.groupRecommendVirtual = false
            params.configForm.groupAuto = false
            params.configForm.groupAutoAfterCreate = 0
            params.configForm.groupAutoBeforeClose = 0
            params.configForm.groupAutoBeforeNum = 0
            params.configForm.groupLeaderDiscount = false
          }

          // 日期
          params.beginTime = params.activityDate[0]
          params.endTime = params.activityDate[1]
          delete params.activityDate

          // sku
          params.skuList.forEach(v => {
            v.price = this.$math.mul(v.price, 100)
            v.specialPrice = this.$math.mul(v.specialPrice || 0, 100)
            v.baseStock = v.baseStock || 0
          })

          // 用户
          if (params.configForm.userLimit !== 2) params.configForm.userLimitCards = []
          // 限购
          if (!params.configForm.perUserLimitSwitch) params.configForm.perUserLimit = 0
          if (!params.configForm.perOrderLimitSwitch) params.configForm.perOrderLimit = 0
          delete params.configForm.perUserLimitSwitch
          delete params.configForm.perOrderLimitSwitch

          console.log('拼团团购表单数据', params)
          this.loading = true
          const apiFun = this.mode === 'add' ? addActivity : updateActivity
          apiFun(params).then(res => {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    /**
     * 状态组
     */
    // 订单支持方式
    changeDeliverySupply() {
      this.$refs.form.validateField(['deliveryList'])
    },

    // 限购
    changePerUserLimit() {
      this.$refs.form.validateField(['configForm.perOrderLimit'])
    },

    // 多选
    changeGroupAutoRuleCheckBox() {
      this.$refs.form.validateField(['configForm.groupAutoAfterCreate', 'configForm.groupAutoBeforeClose', 'configForm.groupAutoBeforeNum'])
    },

    // 团长优惠
    changeGroupLeaderDiscount() {
      if (this.form.skuList.length) {
        const field = []
        this.form.skuList.map((v, i) => {
          field.push(`skuList.${i}.specialPrice`)
        })
        this.$refs.form.validateField(field)
      }
    }
    // changeStoreInventory() {
    //   if (this.form.skuList.length) {
    //     const field = []
    //     this.form.skuList.map((v, i) => {
    //       field.push(`skuList.${i}.baseStock`)
    //     })
    //     this.$refs.form.validateField(field)
    //   }
    // }
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.limited-time-offers-form-main {
  padding: 20px;
  border-radius: 6px;
  background-color: #fff;
  /*head*/
  .head-container {
    height: 45px;
    .title {
      font-size: 20px;
      font-weight: bold;
      margin-right: 20px;
    }

    .el-divider {
      margin: 10px 0 20px;
    }
  }

  /*form*/
  .form-container {
    height:calc(100vh - 205px);
    .w-100 {
      width: 100px;
    }

    .w-200 {
      width: 200px;
    }

    .w-500 {
      width: 500px;
    }

    /*商品信息*/
    .goods-content {
      margin: 10px 0;

      .name {
        font-size: 18px;
        font-weight: bold;
      }
    }

    /* 嵌套盒子 */
    .nest-card-box {
      width: 50%;
      min-width: 600px;
      max-width: 1000px;

      ::v-deep .el-card {
        margin-bottom: 10px;
      }
    }
  }

  /*reset*/
  .el-divider__text {
    font-size: 18px;
    font-weight: bold;
  }

  /* input计数 */
  ::v-deep .el-input__suffix {
    line-height: 32px;
  }
}

</style>
